<?php
/**
 * Created by PhpStorm.
 * User: Sojo
 * Date: 2017/5/31
 * Time: 15:52
 */
namespace App\Http\Admin\Website\Controllers;

use Framework\BaseClass\Http\Admin\Controller;

class IndexController extends Controller
{
    /**
     * 首页
     * @author Sojo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $user = request()->user('admin');
        $username = $user->username;
        $roleName = $user->roles[0]->display_name;

        $topMenuList = $this->getTopMenuList();
        return $this->view('home', compact('topMenuList', 'username', 'roleName'));
    }

    public function getUserList(){
        return json_encode(array('username'=>'admin','pwd'=>'123456'));
    }

    /**
     * 登录
     * @author Sojo
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function loginHome()
    {
        if (\Auth::guard('admin')->check()) return redirect('admin');
        $message = '';
        if (request()->isMethod('post')) {
            try {
                $this->login();
                return redirect()->intended('admin');
            } catch (\DebugError $e) {
                $message = $e->getMessage();
            }
        }
        return $this->view('login', compact('message'));
    }

    private function login()
    {
        $request = app('App\Http\Admin\Requests\Login');
        $isRemember = $request ? true : false;

        if (!\Auth::guard('admin')->attempt(['username' => $request->account, 'password' => $request->password], $isRemember)) {
            request()->flashOnly('account');
            request()->session()->regenerate();
            xThrow(ERR_CLIENT_LOGIN_INFO);
        }

    }

    /**
     * 超时登录
     * @author Sojo
     */
    public function loginTimeout()
    {
        if (request()->isMethod('post')) {
            try {
                $this->login();
                return $this->ajaxSuccess();
            } catch (\DebugError $e) {
                return $this->ajaxFail($e->getMessage());
            }
        }
        return $this->view('login-timeout');
    }

    /**
     * 登出
     * @author Sojo
     */
    public function logout()
    {
        \Auth::guard('admin')->logout();
        request()->session()->flush();
        request()->session()->regenerate();

        return redirect('admin/login');
    }
}
